import React, { Component } from 'react'
import { connect } from 'react-redux'

import { Input, AutoComplete } from 'antd'


class Search extends Component {
    constructor(props) {
        super(props)
        this.state = {
            initOptions: [
            ], 
            options: [],
            value: ''
        }
    }

    onSearch = (value) => {
        this.setState({
            value: value
        })
    }

    onSelect = (value, option) => {
        let focusNode = null
        for(let i = 0; i < this.props.graphData.nodes.length; i++) {
            if(this.props.graphData.nodes[i].name === value) {
                focusNode = this.props.graphData.nodes[i]
            }
        }
        this.focusOnNode(focusNode, this.props.graph)
    }

    focusOnNode = (node, graph) => {
        const distance = 40
        const distRatio = 1 + distance / Math.hypot(node.x, node.y, node.z)

        graph.cameraPosition(
            {
                x: node.x * distRatio,
                y: node.y * distRatio,
                z: node.z * distRatio
            }, 
            node,
            3000
        )
    }

    render() {
        let options = []
        let initOptions = []
        this.props.graphData.nodes.map(node => {
            initOptions.push({ value: node.name })
            return node
        })
        if(this.state.value !== '') {
            initOptions.map(initOption => {
                if(initOption.value.indexOf(this.state.value) === 0) {
                    options.push(initOption)
                }
                return initOption
            })
        }

        

        return (
            <div className="graph-overall-search">
            <AutoComplete
                style={{ width: 300 }}
                options={options}
                onSearch={this.onSearch}
                onSelect={this.onSelect}
            >
                <Input.Search size="large" placeholder="搜索节点..." />
            </AutoComplete>
        </div>
        )
    }
}


const mapStateToProps = (state) => ({
    graphData: state.overall.updateGraph
})


export default connect(mapStateToProps)(Search)